# coding=utf-8
from django.db import models
from django.shortcuts import resolve_url
from jieba.analyse import extract_tags
from mezzanine.core.fields import RichTextField
from mezzanine.generic.fields import RatingField, CommentsField
from mezzanine.generic.models import Keyword, AssignedKeyword
from mezzanine.pages.models import Page, Displayable
from utils import get_pinyin, upload_to


class SyncSource(models.Model):
    '''
    同步源
    '''
    source_name = models.CharField(u'来源名称', max_length=20, null=True, blank=True, help_text=u'标明同步来源')
    source_friendly_name = models.CharField(u'来源友好名称', max_length=20, null=True, blank=True, help_text=u'后台区分的唯一名称')
    sync_source = models.URLField(u'同步地址', max_length=200, null=True, blank=True)
    sync_hook = models.CharField(u'同步程序', max_length=100, null=True, blank=True)

    def __unicode__(self):
        return self.source_friendly_name

    class Meta:
        verbose_name = u'同步源'
        verbose_name_plural = u'同步源'


class Category(Page):
    sync_sources = models.ManyToManyField(SyncSource)

    class Meta:
        verbose_name = u'文章分类'

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = get_pinyin(self.title)[0:50]
            qs = Category.objects.filter(slug=self.slug)
            if qs.exists():
                self.slug += str(qs.count())
            update_fields = kwargs['update_fields'] if 'update_fields' in kwargs else None
            if update_fields and not 'slug' in update_fields:
                update_fields = list(update_fields)
                update_fields.append('slug')
        return super(Category, self).save(*args, **kwargs)


class CategoryRoot(Page):
    '''
    文章分类跟节点。用于收集子级分类(Category)中的信息，形成子级分类的"子门户"页面。类似专题首页。
    '''

    class Meta:
        verbose_name = u'文章分类根'

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = get_pinyin(self.title)[0:50]
            qs = CategoryRoot.objects.filter(slug=self.slug)
            if qs.exists():
                self.slug += str(qs.count())
            update_fields = kwargs['update_fields'] if 'update_fields' in kwargs else None
            if update_fields and not 'slug' in update_fields:
                update_fields = list(update_fields)
                update_fields.append('slug')
        return super(CategoryRoot, self).save(*args, **kwargs)


class Article(Displayable):
    categories = models.ManyToManyField(Category)
    author = models.CharField(max_length=20, null=True, blank=True, verbose_name=u'作者')
    original_url = models.CharField(max_length=300, null=True, blank=True, verbose_name=u'源地址', db_index=True)
    body = RichTextField(verbose_name=u'正文')
    show_order = models.SmallIntegerField(default=0)
    cover = models.ImageField(u'封面', upload_to=upload_to('article'), null=True, blank=True)
    featured = models.BooleanField(u'特色文章', default=False)

    view_count = models.IntegerField(default=0, editable=False)

    rating = RatingField()
    comments = CommentsField()

    search_fields = ("title", 'body')

    class Meta:
        ordering = ('show_order', '-publish_date', '-id')
        index_together = (('show_order', 'publish_date', 'id'),)
        verbose_name = u'文章'
        verbose_name_plural = u'文章'

    def get_absolute_url(self):
        return resolve_url('article_detail', slug=self.slug)

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if not self.slug:
            self.slug = get_pinyin(self.title)[0:20]
            qs = Article.objects.filter(slug=self.slug)
            if qs.exists():
                self.slug += str(qs.count())
            if update_fields and not 'slug' in update_fields:
                update_fields = list(update_fields)
                update_fields.append('slug')
        if not self.description:
            self.gen_description = True  # 指示自动生成描述

        return super(Article, self).save(force_insert, force_update, using, update_fields)

    def gen_keywords(self, body=None):
        if body is None:
            body = self.body
        tags = extract_tags(body, 10)
        for keyword in tags:  # 自动分析keyword
            kw, created = Keyword.objects.get_or_create(title=keyword)
            if created:
                keyword_slug = get_pinyin(keyword)
                i = 2
                while Keyword.objects.filter(slug=keyword_slug).exists():
                    keyword_slug += str(i)
                    i += 1
                kw.slug = keyword_slug
                kw.save()
            self.keywords.add(AssignedKeyword(keyword=kw))

    @property
    def category(self):
        category = getattr(self, '__category', None)
        if not category:
            category = self.categories.all()[0] if self.categories else None
            setattr(self, '__category', category)
        return category

    def get_previous(self):
        previous = getattr(self, '__previous', None)
        if not previous:
            qs = Article.objects.filter(id__lt=self.id).order_by('-id')
            if qs.exists():
                previous = qs[0]
            else:
                previous = None
            setattr(self, '__previous', previous)

        return previous

    def get_next(self):
        _next = getattr(self, '__next', None)
        if not _next:
            qs = Article.objects.filter(id__gt=self.id).order_by('id')
            if qs.exists():
                _next = qs[0]
            else:
                _next = None
            setattr(self, '__next', _next)
        return _next

    def get_related(self, size=10):
        related = getattr(self, '__related', None)
        if not related:
            related = Article.objects.filter(keywords__keyword__in=self.keywords.all()).distinct()[0:size]
            setattr(self, '__related', related)
        return related